// main.go
package main

import (
	"encoding/json"
	"log"
	"net/http"

	"github.com/hashicorp/consul/api"
)

// User 结构体定义
type User struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	Age  int    `json:"age"`
}

// 模拟用户数据
var users = []User{
	{ID: "1", Name: "Alice", Age: 25},
	{ID: "2", Name: "Bob", Age: 30},
}

const (
	WSL_HOST_IP = "172.31.240.1" // WSL_HOST_IP
)

func main() {
	// 1. 注册服务到Consul
	serviceID := registerService()
	defer deregisterService(serviceID)

	// 2. 启动HTTP服务
	http.HandleFunc("/users", getUsers)
	http.HandleFunc("/health", healthCheck)
	http.HandleFunc("/", healthCheck)

	log.Println("用户服务已启动，监听端口:8081")
	if err := http.ListenAndServe(":8081", nil); err != nil {
		log.Fatalf("服务启动失败: %v", err)
	}
}

// 获取所有用户
func getUsers(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(users)
}

// 健康检查
func healthCheck(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	w.Write([]byte("OK"))
}

// 注册服务到Consul
func registerService() string {
	config := api.DefaultConfig()
	config.Address = "localhost:8500" // 显式指定 IPv4 地址
	client, err := api.NewClient(config)
	if err != nil {
		log.Fatalf("连接Consul失败: %v", err)
	}

	http1 := "http://" + WSL_HOST_IP + ":8081/health"

	serviceID := "user-service-1"
	registration := &api.AgentServiceRegistration{
		ID:      serviceID,
		Name:    "user-service",
		Address: WSL_HOST_IP,
		Port:    8081,
		Tags:    []string{"go", "user"},
		Check: &api.AgentServiceCheck{
			HTTP:     http1,
			Interval: "10s",
			Timeout:  "3s",
		},
	}

	if err := client.Agent().ServiceRegister(registration); err != nil {
		log.Fatalf("服务注册失败: %v", err)
	}

	log.Println("服务已注册到Consul:", serviceID)
	return serviceID
}

// 从Consul注销服务
func deregisterService(serviceID string) {
	config := api.DefaultConfig()
	client, err := api.NewClient(config)
	if err != nil {
		log.Printf("连接Consul失败: %v", err)
		return
	}

	if err := client.Agent().ServiceDeregister(serviceID); err != nil {
		log.Printf("服务注销失败: %v", err)
	} else {
		log.Println("服务已从Consul注销:", serviceID)
	}
}
